package com.vv.server;

import mapper.Context;
import mapper.Host;
import mapper.Service;
import mapper.Wrapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String,HttpServlet> servletMap;
    private Service service;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap,Service service) {
        this.socket = socket;
        this.servletMap = servletMap;
        this.service = service;
    }

    public RequestProcessor(Socket socket, Service service) {
        this.socket = socket;
        this.service = service;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String hostStr = request.getHost();

            String url = request.getUrl();
            if(hostStr.equals(service.getName())){
                String contextStr = url.split("/")[1];
                Context context = service.getHost().findContext(contextStr);
                if(context != null){
                    String servletUrl = url.replace("/"+contextStr,"");
                    Wrapper wrapper = context.findWrapper(servletUrl);
                    HttpServlet httpServlet = wrapper.getServlet();
                    // 静态资源处理
                    if(httpServlet == null) {
                        response.outputHtml(servletUrl);
                    }else{
                        // 动态资源servlet请求
                        httpServlet.service(request,response);
                    }
                }else{
                    // 输出404
                    response.output(HttpProtocolUtil.getHttpHeader404());
                }

            }else{
                // 输出404
                response.output(HttpProtocolUtil.getHttpHeader404());
            }

            // 静态资源处理
//            if(servletMap.get(request.getUrl()) == null) {
//                response.outputHtml(request.getUrl());
//            }else{
//                // 动态资源servlet请求
//                HttpServlet httpServlet = servletMap.get(request.getUrl());
//                httpServlet.service(request,response);
//            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
